<template>
  <!-- 监听页面滚动 -->
  <div class="scroll-to-top">
    <button id="btn" @click="backTopBtn"><slot name="ico"></slot></button>
  </div>
</template>

<script setup>
import { defineProps, onMounted } from 'vue'
const props = defineProps({
  duration: {
    type: Number,
    default: 3000
  },
  topPx: {
    type: Number,
    default: 0
  },
  behavior: {
    type: String,
    default: 'smooth'
  }
})

const backTopBtn = () => {
  window.scroll({
    top: props.topPx,
    behavior: props.behavior,
    duration: props.duration
  })
}

const isShowScroll = (elementId) => {
  const element = document.getElementById(elementId)
  var scrollPosition = window.scrollY
  window.addEventListener('scroll', function () {
    scrollPosition = window.scrollY
    if (scrollPosition === 0) {
      element.style.opacity = 0
    } else if (scrollPosition >= 100) {
      element.style.opacity = scrollPosition / 10
    }
  })
}

onMounted(() => {
  isShowScroll('btn')
})
</script>

<style scoped lang="scss">
.scroll-to-top {
  width: 50px;
  height: 50px;
  position: fixed;
  right: 15px;
  bottom: 20px;

  #btn {
    $b: #44b8f3;
    color: #eee;
    background: $b;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    border: none;
    cursor: pointer;
    font-size: 18px;
    opacity: 0;
    transition: all 1s;

    &:hover {
      background: lighten($b, 10%);
    }
    &:active {
      background: darken($b, 5%);
    }
  }
}
</style>
